package cn.gdpu.course.web.controller;

import cn.gdpu.course.constant.Constant;
import cn.gdpu.course.dao.AdminDao;
import cn.gdpu.course.dao.StudentDao;
import cn.gdpu.course.dao.TeacherDao;
import cn.gdpu.course.dao.domain.Admin;
import cn.gdpu.course.dao.domain.Student;
import cn.gdpu.course.dao.domain.Teacher;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Random;

/**
 * Created by Administrator on 2018/3/13.
 */

@Controller
@RequestMapping("/")
public class LoginController {

	@Resource
	private StudentDao studentDao;

	@Resource
	private AdminDao adminDao;

	@Resource
	private TeacherDao teacherDao;

	@RequestMapping(method = RequestMethod.GET)
	public String index(ModelMap model) {
		return "login";
	}

	/**
	 * 获取验证码
	 *
	 * @param response
	 * @param session
	 */
	@RequestMapping("/getVerifyCode")
	public void generate(HttpServletResponse response, HttpSession session) {
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		String verifyCodeValue = drawImg(output);

		session.setAttribute("verifyCodeValue", verifyCodeValue);

		try {
			ServletOutputStream out = response.getOutputStream();
			output.writeTo(out);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 绘画验证码
	 *
	 * @param output
	 * @return
	 */
	private String drawImg(ByteArrayOutputStream output) {
		String code = "";
		// 随机产生4个字符
		for (int i = 0; i < 4; i++) {
			code += randomChar();
		}
		int width = 70;
		int height = 25;
		BufferedImage bi = new BufferedImage(width, height,
				BufferedImage.TYPE_3BYTE_BGR);
		Font font = new Font("Times New Roman", Font.PLAIN, 20);
		// 调用Graphics2D绘画验证码
		Graphics2D g = bi.createGraphics();
		g.setFont(font);
		Color color = new Color(66, 2, 82);
		g.setColor(color);
		g.setBackground(new Color(226, 226, 240));
		g.clearRect(0, 0, width, height);
		FontRenderContext context = g.getFontRenderContext();
		Rectangle2D bounds = font.getStringBounds(code, context);
		double x = (width - bounds.getWidth()) / 2;
		double y = (height - bounds.getHeight()) / 2;
		double ascent = bounds.getY();
		double baseY = y - ascent;
		g.drawString(code, (int) x, (int) baseY);
		g.dispose();
		try {
			ImageIO.write(bi, "jpg", output);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return code;
	}

	/**
	 * 随机参数一个字符
	 *
	 * @return
	 */
	private char randomChar() {
		Random r = new Random();
		String s = "ABCDEFGHJKLMNPRSTUVWXYZ0123456789";
		return s.charAt(r.nextInt(s.length()));
	}

	@ResponseBody
	@RequestMapping(value = "login", method = RequestMethod.POST)
	public int studentLogin(HttpServletRequest request, String username, String password, int role) {
		String inputVerifyCode=request.getParameter("verifyCode");
		String verifyCodeValue= (String)request.getSession().getAttribute("verifyCodeValue");
		if (role == 1) {//学生身份
			Student student = new Student();
			student.setSno(username);
			Student stu = studentDao.findBySno(student);
			if (stu == null) {
				return -1;//无数据
			} else {
				if (password.equals(stu.getPassword())) {
					if(verifyCodeValue.equals(inputVerifyCode.toUpperCase())){
						request.getSession().setAttribute(Constant.student_login_session_name, stu.getSno());
						request.getSession().setAttribute(Constant.user_id, stu.getId());
						request.getSession().setAttribute(Constant.user_name, stu.getSname());
						return 1;//成功
					} else {
						return -3;
					}
//					request.getSession().setAttribute(Constant.student_login_session_name, stu.getSno());
//					request.getSession().setAttribute(Constant.user_id, stu.getId());
//					request.getSession().setAttribute(Constant.user_name, stu.getSname());
//					return 1;//成功
				} else {
					return -2;//密码不正确
				}
			}
		} else if (role == 2) {//管理员身份
			Admin admin = new Admin();
			admin.setAno(username);
			Admin adm = adminDao.findByAno(admin);
			if (adm == null) {
				return -1;//无数据
			} else {
				if (password.equals(adm.getPassword())) {
					if(verifyCodeValue.equals(inputVerifyCode.toUpperCase())){
						request.getSession().setAttribute(Constant.admin_login_session_name, adm.getAno());
						request.getSession().setAttribute(Constant.user_id, adm.getId());
						request.getSession().setAttribute(Constant.user_name, adm.getAname());
						return 1;//成功
					} else {
						return -3;
					}
//					request.getSession().setAttribute(Constant.admin_login_session_name, adm.getAno());
//					request.getSession().setAttribute(Constant.user_id, adm.getId());
//					request.getSession().setAttribute(Constant.user_name, adm.getAname());
//					return 1;//成功
				} else {
					return -2;//密码不正确
				}
			}
		} else if (role == 3) {//教师身份
//			System.out.println(username);
			Teacher teacher = new Teacher();
			teacher.setTno(username);
			Teacher tea = teacherDao.findByTno(teacher);
			if (tea == null) {
//				System.out.println(1);
				return -1;//无数据
			} else {
				if (password.equals(tea.getPassword())) {
					if (verifyCodeValue.equals(inputVerifyCode.toUpperCase())) {
						request.getSession().setAttribute(Constant.teacher_login_session_name, tea.getTno());
						request.getSession().setAttribute(Constant.user_id, tea.getId());
						request.getSession().setAttribute(Constant.user_name, tea.getTname());
						return 1;//成功
					} else {
						return -3;
					}
//					request.getSession().setAttribute(Constant.teacher_login_session_name, tea.getTno());
//					request.getSession().setAttribute(Constant.user_id, tea.getId());
//					request.getSession().setAttribute(Constant.user_name, tea.getTname());
////					System.out.println(tea.getTno()+tea.getId()+tea.getTname());
//					return 1;//成功
				} else {
					return -2;//密码不正确
				}
			}
		} else {
			return 0;
		}
	}

	@RequestMapping(value = "logout", method = RequestMethod.GET)
	public String logout(HttpServletRequest request) {
		request.getSession().setAttribute(Constant.student_login_session_name, null);
		request.getSession().setAttribute(Constant.admin_login_session_name, null);
		request.getSession().setAttribute(Constant.teacher_login_session_name, null);
		return "login";

	}

}
